using UnityEngine;
using UI;
using Math;

public class PerlinMesh : GUIMeshNode
{
    private GameObject renderTextureCam;
    private bool isDragging = false;
    private float X = 0.0f;
    private float Y = -45.0f;
    private Vector3 meshPosition = Vector3.zero;
    private Quaternion meshRotation = Quaternion.identity;

    public int Dimensions = 128;
    public RenderTexture Texture;
    public Mesh Mesh;
    public Material Material;
    public Color Background = Color.gray;

    public float CamFov = 45.0f;
    public float Distance = 1.4f;
    public float DistanceMin = 1.0f;
    public float DistanceMax = 5.0f;

    public float XSpeed = 500.0f;
    public float YSpeed = 500.0f;

    public float YMinLimit = -90.0f;
    public float YMaxLimit = 90.0f;

    void Awake()
    {
        renderTextureCam = new GameObject("RenderTextureCamera", typeof(Camera));
        renderTextureCam.camera.enabled = false;
        renderTextureCam.hideFlags = HideFlags.HideInHierarchy;
    }

    void Start()
    {
        Width = Dimensions;
        Height = Dimensions;

        Texture = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);
    }

    public override void DrawGUI()
    {
        Rect rect = new Rect(PositionX, PositionY, Width, Height);

        GUI.DrawTexture(rect, Texture, ScaleMode.ScaleAndCrop, false);
        GUI.Label(new Rect(PositionX, PositionY+Height, Width, 50.0f), name);

        isDragging = Mouse.UpdateDrag(isDragging, rect);
    }

    void Update()
    {
        if (isDragging)
        {
            X -= Input.GetAxisRaw("Mouse X") * XSpeed * Distance * 0.02f;
            Y += Input.GetAxisRaw("Mouse Y") * YSpeed * 0.02f;
            Y = Maths.ClampAngle(Y, YMinLimit, YMaxLimit);
        }
        meshRotation = Quaternion.Euler(Y, 0.0f, 0.0f) * Quaternion.Euler(0.0f, X, 0.0f);
        meshPosition = new Vector3(0.0f, 0.0f, Distance);

        DrawMesh(renderTextureCam.camera);
    }

    private void DrawMesh(Camera camera)
    {
        camera.CopyFrom(Camera.mainCamera);
        camera.cullingMask         = Camera.mainCamera.cullingMask;
        camera.clearFlags          = CameraClearFlags.Color;
        camera.backgroundColor     = Background;
        camera.transform.position  = Vector3.zero;
        camera.fov                 = CamFov;
        camera.targetTexture       = Texture;

        Material.SetPass(0);
        Graphics.DrawMesh(Mesh, meshPosition, meshRotation, Material, 0, camera);

        camera.RenderWithShader(Material.shader, null);
    }
}